/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 保管费统计
 */
import React, { Component } from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { connect } from 'dva';
import { Form, DatePicker, Button } from 'antd';
import moment from 'moment/moment';
import { debounce } from 'lodash';
import StandardTable from '@/components/StandardTable';
import { Yzs, Brands } from '@/components/Select';
import AsyncDownLoad from '@/components/DownloadBar/AsyncDownLoad';
import styles from './style.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
@connect(({ loading, dispat, report, list }) => ({
  dispat,
  report,
  list,
  stationing: loading.effects['area/subList'],
  getStorageStatisticsRecord: loading.effects['dispat/getStorageStatisticsRecord'],
}))
@Form.create()
class StorageFeeStatistics extends Component {
  handleStandardTableChange = debounce(
    pagination => {
      // 首页表格分页
      const { dispatch } = this.props;
      const { formValues } = this.state;
      const params = {
        page: pagination.current,
        ...formValues,
        dl: 0,
      };
      dispatch({
        type: 'dispat/getStorageStatisticsRecord',
        payload: params,
      });
      this.setState({
        currentPage: pagination.current,
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  handleSearchForthe = debounce(
    e => {
      e.preventDefault();
      const { dispatch } = this.props;

      this.getFormValues(values => {
        if (!values.cm_id) {
          values.cm_id = '';
        }
        dispatch({
          type: 'dispat/getStorageStatisticsRecord',
          payload: {
            ...values,
            cm_id: values.cm_id,
            page: 1,
            dl: 0,
          },
        });
        this.setState({
          cm_id: values.cm_id,
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    this.state = {
      feeDetail_start: moment()
        .startOf('day')
        .subtract(7, 'days'),
      feeDetail_end: moment()
        .endOf('day')
        .subtract(1, 'days'),
      cm_id: '',
      currentPage: 1,
      formValues: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { currentPage } = this.state;
    this.getFormValues(values => {
      if (!values.cm_id) {
        values.cm_id = '';
      }
      dispatch({
        type: 'dispat/getStorageStatisticsRecord',
        payload: {
          ...values,
          page: currentPage,
          dl: 0,
        },
      });
    });
  }

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.beginDate = start;
        values.endDate = end;
        delete values.date;
      }
      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  disabledDate = current =>
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(0, 'days');

  dataClick = data => {
    const { form } = this.props;
    const setFieldsValueDate = {
      startDate: moment()
        .startOf('day')
        .subtract(data, 'days'),
      endDate: moment()
        .endOf('day')
        .subtract(1, 'days'),
    };
    form.setFieldsValue({
      date: [setFieldsValueDate.startDate, setFieldsValueDate.endDate],
    });
  };

  onExportValue = () => {
    const { formValues, currentPage } = this.state;
    const data = {
      ...formValues,
      dl: 1,
      page: currentPage,
    };
    return data;
  };

  render() {
    const { feeDetail_start, feeDetail_end, cm_id, formValues, currentPage } = this.state;
    const {
      dispat: { statisticsList, summery },
      form,
      getStorageStatisticsRecord,
    } = this.props;
    const { getFieldDecorator } = form;
    const { total_fee, total_num } = summery;
    const columns = [
      {
        title: '日期',
        dataIndex: 'days',
        key: 'days',
      },
      {
        title: '驿站名称',
        dataIndex: 'yz_name',
        key: 'to_kb_id',
      },
      {
        title: `入库数${total_num || 0}条`,
        dataIndex: 'in_count',
        key: 'num',
      },
      {
        title: `入库保管费${total_fee || 0}元`,
        dataIndex: 'fee_sum',
        key: 'fee',
      },
    ];
    return (
      <div style={{ paddingTop: 10 }}>
        <div>
          <Form
            onSubmit={this.handleSearchForthe}
            className={styles['search-form']}
            layout="inline"
          >
            <FormItem>
              <a className={styles.select_date} onClick={() => this.dataClick(1)}>
                昨日
              </a>
              <a className={styles.select_date} onClick={() => this.dataClick(7)}>
                近7日
              </a>
              <a className={styles.select_date} onClick={() => this.dataClick(30)}>
                近30日
              </a>
            </FormItem>
            <FormItem className={styles.data}>
              {getFieldDecorator('date', {
                initialValue: [moment(feeDetail_start), moment(feeDetail_end)],
              })(
                <RangePicker
                  style={{ width: '280px' }}
                  placeholder={['开始日期', '结束日期']}
                  disabledDate={this.disabledDate}
                />,
              )}
            </FormItem>
            <FormItem className={styles.data}>
              {getFieldDecorator('cm_id', {
                initialValue: cm_id,
              })(<Yzs style={{ width: 200 }} allowClear />)}
            </FormItem>
            <FormItem className={styles.data}>
              {getFieldDecorator('brand', {})(<Brands style={{ width: 200 }} allowClear />)}
            </FormItem>
            <FormItem>
              <span className={styles.submitButtons}>
                <Button
                  type="primary"
                  htmlType="submit"
                  key="search"
                  loading={getStorageStatisticsRecord}
                  icon="search"
                >
                  查询
                </Button>
              </span>
              <div
                style={{
                  paddingBottom: '24px',
                  marginLeft: '16px',
                  display: 'inline-block',
                }}
              >
                <AsyncDownLoad
                  action="/Api/YZ/Fund/getStorageFee"
                  method="POST"
                  data={this.onExportValue}
                >
                  <Button type="primary" icon="download">
                    下载
                  </Button>
                </AsyncDownLoad>
              </div>
              <div
                style={{
                  paddingBottom: '24px',
                  marginLeft: '16px',
                  display: 'inline-block',
                }}
              >
                <AsyncDownLoad
                  action="/Api/YZ/Fund/getStorageFee"
                  method="POST"
                  data={() => ({
                    ...formValues,
                    dl: 2,
                    page: currentPage,
                  })}
                >
                  <Button type="primary" icon="download">
                    下载全部明细
                  </Button>
                </AsyncDownLoad>
              </div>
            </FormItem>
          </Form>
          <StandardTable
            rowKey={record => record.cm_id}
            loading={getStorageStatisticsRecord}
            data={statisticsList}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </div>
    );
  }
}

export default StorageFeeStatistics;
